#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include "../inc/Message.h"

// 发消息
int sendMessage(int clientFd, Message *message)
{
    int type = message->type;
    int length = message->length;
    char* content = message->content;
    if (length < 1 || type < 0 || content == NULL)
    {
        return -1;
    }
    // 构造要发送的数据
    char *data = (char*)calloc(1, length + 4 + 4);
    int bigType = htonl(type);
    memcpy(data, &bigType, 4);
    int bigLength = htonl(length);
    memcpy(data + 4, &bigLength, 4);
    memcpy(data + 8, content, length);

    int bytes_received = 0;
    // 内容长度
    int totalLength = message->length + 8;
    // 未发送的长度
    int remaining_length = message->length + 8;

    // 发送消息内容，直到完整接收
    while (remaining_length > 0)
    {
        bytes_received = send(clientFd, data + (totalLength - remaining_length), remaining_length, 0);
        if (bytes_received < 0)
        {
            perror("错误");
            free(data);
            return -1;
        }
        remaining_length -= bytes_received;
    }
    free(data);
    return totalLength;
}
int readn(int fd,char* buf,int size){
    //指向缓冲区
    char *p=buf;
    //记录剩余字节数
    int count=size;
    while (count>0)
    {
        int len=recv(fd,p,count,0);
        if (len==-1)
        {
            perror("recv");
            return -1;
        }else if (len==0)
        {
            return size-count;
        }
        p+=len;
        count-=len;
    }
    return size;
}
// 收消息
Message *receiveMessage(int clientFd)
{
    Message *msg=(Message*)calloc(1,sizeof(Message));

    //先读type
    int type=-1;
    int bytes_read = readn(clientFd,(char*)&type,4);
    if (bytes_read <= 0) {
        free(msg);
        return NULL; // 连接关闭
    }
    type=ntohl(type);
    //再读length
    int len=-1;
    bytes_read = readn(clientFd,(char*)&len,4);
    if (bytes_read <= 0) {
        free(msg);
        return NULL; // 连接关闭
    }
    len =ntohl(len);
    //最后读数据
    char* content=(char*)calloc(1,len);
    bytes_read = readn(clientFd,content,len);
    if (bytes_read <= 0) {
        free(content);
        free(msg);
        return NULL; // 连接关闭
    }

    msg->type=type;
    msg->length=len;
    msg->content=content;
    return msg;
}
